package com.yanqu.road.server.manager.kuang.activity;

import com.google.protobuf.AbstractMessage;
import com.yanqu.road.entity.config.system.PropertyWeightItem;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.enums.kuang.eKuangAttributeType;
import com.yanqu.road.entity.kuang.KuangConfig;
import com.yanqu.road.entity.kuang.KuangRankRewardConfig;
import com.yanqu.road.entity.kuang.config.KuangSystemConfig;
import com.yanqu.road.entity.kuang.config.entity.KuangTimeConfig;
import com.yanqu.road.entity.kuang.group.KuangMatchGroup;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.servercenter.ChannelSystemConfig;
import com.yanqu.road.logic.bussiness.kuang.KuangBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.kuang.Kuang;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.config.BattleChannelSystemConfigMgr;
import com.yanqu.road.server.manager.config.CrossChannelSystemConfigMgr;
import com.yanqu.road.server.manager.kuang.CrossKuangMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.manger.ChannelSystemConfigMgr;
import com.yanqu.road.server.protocol.AgentProtocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossKuangBaseActivity {

    protected static Logger logger = LogManager.getLogger(CrossKuangBaseActivity.class.getName());

    /**
     * 锁
     */
    protected final Object lock = new Object();

    /**
     * 活动配置
     */
    protected KuangConfig config = null;


    public CrossKuangBaseActivity() {

    }

    public void reloadConfig() {
        // 加载后台配置
        int channelId = ConfigHelper.getInt("channelId");
        Map<String, ChannelSystemConfig> systemConfigMap = BattleChannelSystemConfigMgr.getSystemConfigMap(channelId, eSystemId.Kuang.getValue());
        if (systemConfigMap == null) {
            logger.error("矿场配置未加载");
            return;
        }
        KuangConfig kuangConfig = new KuangConfig();
        kuangConfig.setPlaceConfigMap(KuangBusiness.getKuangPlaceConfigMap());

        // 最大属性值
        Map<eKuangAttributeType, Long> maxAttributeMap = new ConcurrentHashMap<>();
        List<String> maxAttributeList = StringUtils.stringToStringList(GameConfig.KUANG_ATTRIBUTE_VALUE_MAX, "\\|");
        for (String s : maxAttributeList) {
            String[] split = s.split("=");
            maxAttributeMap.put(eKuangAttributeType.forValue(Integer.parseInt(split[0])), Long.valueOf(split[1]));
        }
        kuangConfig.setMaxAttributeMap(maxAttributeMap);

        // 争夺战时间
        // 矿场争夺战开启自动报名时间|活动准备期开始时间|开战前准备期时间|活动开始时间|领奖期开始|领奖期结束时间（按星期，配置分钟，星期一零点为0）
        List<Long> kuangTimeList = StringUtils.stringToLongList(GameConfig.KUANG_TIME, "\\|");
        long weekStartTime = DateHelper.getThisWeekStartTime(GameConfig.DAY_SYSTEM_RESET_TIME);
        // 矿场争夺战开启自动报名时间
        KuangTimeConfig timeConfig = new KuangTimeConfig();
        // 时间需要减掉前几天
        weekStartTime = weekStartTime - (GameConfig.DAY_SYSTEM_RESET_TIME - 1) * DateHelper.DAY_MILLIONS;
        // 展示期开始时间/开启自动报名时间
        timeConfig.setBeginShowTime(weekStartTime + kuangTimeList.get(0) * 60L * 1000L);
        // 首日活动打造装备准备期开始时间
        timeConfig.setDay1BeginTime(weekStartTime + kuangTimeList.get(1) * 60L * 1000L);
        // 首日开战前准备期时间
        timeConfig.setDay1BattlePrepareTime(weekStartTime + kuangTimeList.get(2) * 60L * 1000L);
        // 首日活动战斗开始时间
        timeConfig.setDay1BattleStartTime(weekStartTime + kuangTimeList.get(3) * 60L * 1000L);
        // 首日活动战斗结束时间
        timeConfig.setDay1BattleEndTime(weekStartTime + kuangTimeList.get(4) * 60L * 1000L);
        // 次日活动打造装备准备期开始时间
        timeConfig.setDay2BeginTime(weekStartTime + kuangTimeList.get(5) * 60L * 1000L);
        // 次日开战前准备期时间
        timeConfig.setDay2BattlePrepareTime(weekStartTime + kuangTimeList.get(6) * 60L * 1000L);
        // 次日活动战斗开始时间
        timeConfig.setDay2BattleStartTime(weekStartTime + kuangTimeList.get(7) * 60L * 1000L);
        // 次日活动战斗结束时间/领奖期开始
        timeConfig.setDay2BattleEndTime(weekStartTime + kuangTimeList.get(8) * 60L * 1000L);
        // 领奖期结束时间
        timeConfig.setRewardEndTime(weekStartTime + kuangTimeList.get(9) * 60L * 1000L);
        kuangConfig.setTimeConfig(timeConfig);
        // 积分达成条件
        kuangConfig.setBattleScoreEndCondition(GameConfig.KUANG_PVP_BATTLE_TIME_END_CONDITION);

        // 头像半径
        List<String> profileRadius = StringUtils.stringToStringList(GameConfig.KUANG_PVP_PROFILE_RADIUS, "\\|");
        for (String radius : profileRadius) {
            kuangConfig.getProfileRadiusList().add(StringUtils.stringToIntegerList(radius, ";"));
        }

        // 财神技能效果
        List<String> skillParamList = StringUtils.stringToStringList(GameConfig.KUANG_PLAYER_SKILL_WEALTH_PARAM, "#");
        Map<Integer, Map<Integer,Integer>> skillParamMap = new ConcurrentHashMap<>();
        for (int i = 0; i < skillParamList.size(); i++) {
            int littleType = i + 1;
            Map<Integer,Integer> map = new HashMap<>();
            String skillParam = skillParamList.get(i);
            List<String> paramList = StringUtils.stringToStringList(skillParam, "\\|");
            for (String param : paramList) {
                List<Integer> p = StringUtils.stringToIntegerList(param, ";");
                map.put(p.get(0), p.get(1));
            }
            skillParamMap.put(littleType, map);
        }
        kuangConfig.setSkillParamMap(skillParamMap);

        KuangSystemConfig kuangSystemConfig = new KuangSystemConfig();
        // 矿场消耗
        ChannelSystemConfig kuangshanLotteryCost = systemConfigMap.get("KUANGSHAN_LOTTERY_COST");
        if (kuangshanLotteryCost == null) {
            logger.error("矿场配置KUANGSHAN_LOTTERY_COST不存在");
            return;
        }
        kuangSystemConfig.setLotteryCost(PropertyHelper.parseStringToProperty(kuangshanLotteryCost.getValue()));
        // 矿场宝库数量
        ChannelSystemConfig kuangshanLotteryBoxNum = systemConfigMap.get("KUANGSHAN_LOTTERY_BOX_NUM");
        if (kuangshanLotteryBoxNum == null) {
            logger.error("矿场配置KUANGSHAN_LOTTERY_BOX_NUM不存在");
            return;
        }
        kuangSystemConfig.setLotteryBoxNum(Integer.parseInt(kuangshanLotteryBoxNum.getValue()));
        // 个人战绩排行榜奖励
        ChannelSystemConfig kuangshanRewardPerson = systemConfigMap.get("KUANGSHAN_REWARD_PERSON");
        if (kuangshanRewardPerson == null) {
            logger.error("矿场配置KUANGSHAN_REWARD_PERSON不存在");
            return;
        }
        String rewardPerson = kuangshanRewardPerson.getValue();
        Map<Integer, List<KuangRankRewardConfig>> personRankRewardMap = new ConcurrentHashMap<>();
        List<String> person1 = StringUtils.stringToStringList(rewardPerson, "\\|");
        for (String person2 : person1) {
            String[] split = person2.split(":");
            int openDay = Integer.parseInt(split[0]);
            List<KuangRankRewardConfig> list = new ArrayList<>();
            String person3 = split[1];
            String[] split1 = person3.split("#");
            for (String person4 : split1) {
                KuangRankRewardConfig rankRewardConfig = new KuangRankRewardConfig();
                String[] split2 = person4.split("-");
                int minRank = Integer.parseInt(split2[0]);
                int maxRank = Integer.parseInt(split2[1]);
                kuangConfig.setPersonMaxRank(Math.max(kuangConfig.getPersonMaxRank(), maxRank));
                String person5 = split2[2];
                rankRewardConfig.setMinRank(minRank);
                rankRewardConfig.setMaxRank(maxRank);
                rankRewardConfig.setReward(person5);
                list.add(rankRewardConfig);
            }
            personRankRewardMap.put(openDay, list);
        }
        kuangSystemConfig.setPersonRankRewardConfigMap(personRankRewardMap);
        // 阵营积分榜奖励配置
        ChannelSystemConfig kuangshanRewardGroup = systemConfigMap.get("KUANGSHAN_REWARD_GROUP");
        if (kuangshanRewardGroup == null) {
            logger.error("矿场配置KUANGSHAN_REWARD_GROUP不存在");
            return;
        }
        String rewardGroup = kuangshanRewardGroup.getValue();
        Map<Integer, List<KuangRankRewardConfig>> groupRankRewardMap = new ConcurrentHashMap<>();
        List<String> group1 = StringUtils.stringToStringList(rewardGroup, "\\|");
        for (String group2 : group1) {
            String[] split = group2.split(":");
            int openDay = Integer.parseInt(split[0]);
            List<KuangRankRewardConfig> list = new ArrayList<>();
            String group3 = split[1];
            String[] split1 = group3.split("#");
            for (String group4 : split1) {
                KuangRankRewardConfig rankRewardConfig = new KuangRankRewardConfig();
                String[] split2 = group4.split("-");
                int minRank = Integer.parseInt(split2[0]);
                int maxRank = Integer.parseInt(split2[1]);
                kuangConfig.setGroupMaxRank(Math.max(kuangConfig.getGroupMaxRank(), maxRank));
                String group5 = split2[2];
                rankRewardConfig.setMinRank(minRank);
                rankRewardConfig.setMaxRank(maxRank);
                rankRewardConfig.setReward(group5);
                list.add(rankRewardConfig);
            }
            groupRankRewardMap.put(openDay, list);
        }
        kuangSystemConfig.setGroupRankRewardConfigMap(groupRankRewardMap);
        // 矿山-宝库普通奖励
        Map<Integer, List<PropertyWeightItem>> lotteryGeneraReward = new ConcurrentHashMap<>();
        ChannelSystemConfig kuangshanLotteryGenera = systemConfigMap.get("KUANGSHAN_LOTTERY_GENERAL");
        if (kuangshanLotteryGenera == null) {
            logger.error("矿场配置KUANGSHAN_LOTTERY_GENERAL不存在");
            return;
        }
        String lotteryGenera = kuangshanLotteryGenera.getValue();
        List<String> genera1 = StringUtils.stringToStringList(lotteryGenera, "\\|");
        for (String genera2 : genera1) {
            String[] split = genera2.split(":");
            int openDay = Integer.parseInt(split[0]);
            String genera3 = split[1];
            List<PropertyWeightItem> list = new ArrayList<>();
            List<String> genera4  = StringUtils.stringToStringList(genera3, ";");
            for (String genera5 : genera4) {
                PropertyWeightItem propertyWeightItem = new PropertyWeightItem();
                List<Integer> genera6 = StringUtils.stringToIntegerList(genera5, "=");
                propertyWeightItem.setProperty(new Property(genera6.get(0), genera6.get(1)));
                propertyWeightItem.setWeight(genera6.get(2));
                list.add(propertyWeightItem);
            }
            lotteryGeneraReward.put(openDay, list);
        }
        kuangSystemConfig.setLotteryGeneraRewardMap(lotteryGeneraReward);
        // 矿山-宝库大奖奖励
        Map<Integer, List<PropertyWeightItem>> lotterySpecialReward = new ConcurrentHashMap<>();
        ChannelSystemConfig kuangshanLotterySpecial = systemConfigMap.get("KUANGSHAN_LOTTERY_SPECIAL");
        if (kuangshanLotterySpecial == null) {
            logger.error("矿场配置KUANGSHAN_LOTTERY_SPECIAL不存在");
            return;
        }
        String lotterySpecial = kuangshanLotterySpecial.getValue();
        List<String> special1 = StringUtils.stringToStringList(lotterySpecial, "\\|");
        for (String special2 : special1) {
            String[] split = special2.split(":");
            int openDay = Integer.parseInt(split[0]);
            String special3 = split[1];
            List<PropertyWeightItem> list = new ArrayList<>();
            List<String> special4  = StringUtils.stringToStringList(special3, ";");
            for (String special5 : special4) {
                PropertyWeightItem propertyWeightItem = new PropertyWeightItem();
                List<Integer> special6 = StringUtils.stringToIntegerList(special5, "=");
                propertyWeightItem.setProperty(new Property(special6.get(0), special6.get(1)));
                propertyWeightItem.setWeight(special6.get(2));
                list.add(propertyWeightItem);
            }
            lotterySpecialReward.put(openDay, list);
        }
        kuangSystemConfig.setLotterySpecialRewardMap(lotterySpecialReward);
        kuangConfig.setKuangSystemConfig(kuangSystemConfig);
        config = kuangConfig;
    }

    public KuangConfig getConfig() {
        return config;
    }

    protected void sendPacket(int code, AbstractMessage.Builder<?> messageBuilder, long userId) {
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
        if (userBaseInfo == null) {
            return;
        }
        YanQuMessage message = YanQuMessageUtils.buildMessage(code, messageBuilder);
        MessageHelper.sendPacket(userBaseInfo.getServerId(), userId, message);
    }

    protected void sendPacketToAll(int weekId, int groupId, int code, AbstractMessage.Builder<?> messageBuilde, Collection<Long> userIdList) {
        KuangMatchGroup matchGroup = CrossKuangMgr.getMatchGroup(weekId, groupId);
        if (matchGroup == null) {
            // 找不到分组
            return;
        }

        // 检查 userIdList 是否为空或大小为负数
        if (userIdList == null || userIdList.size() <= 0) {
            return;
        }
        Kuang.KuangAgentTransferMsg.Builder agentMsg = Kuang.KuangAgentTransferMsg.newBuilder();
        agentMsg.setCode(code);
        agentMsg.addAllUserId(userIdList);
        agentMsg.setMsg(messageBuilde.build().toByteString());

        YanQuMessage message = YanQuMessageUtils.buildMessage(AgentProtocol.A_KUANG_TRANSFER, agentMsg);
        // 获取下分组的服务器列表
        for (Long serverId : matchGroup.getServerIdList()) {
            MessageHelper.sendPacket(serverId, 0, message);
        }
    }

}
